//获取应用实例-在appjs中

var WxParse = require('../../utils/wxParse/wxParse.js');
var http = require('../../service/http.js'); //请求类
var util = require('../../utils/util.js'); //工具类
const Day = 86400000; //毫秒ms
const app = getApp();
var rd_session = '';

var progress = ''; //用于清除加载进度条
//用于保存BMap.search接口返回的数据
var wxMarkerData = [];
Page({
  /**
   * 页面的初始数据
   */
  data: {
    //---当前页名称--------------
    pageName: 'product',
    showLoadding: true, //加载动画gif
    //回到顶部--------------------------------
    scroll_top: 0, //初始化滚动条距离顶部位置
    showTopBtn: false, //是否显示回到顶部
    scrollViewHeight: 0, //滚动窗口高度

    windowWidth: '', //窗口宽度
    windowHeight: '', //窗口高度

    //-----登录------------------------------
    isshow: false, //是否显示mask
    isLogin: false, //是否点击了登录按钮
    isAuthorization: false, //是否授权登陆

    toBuy: false, //是否是立即购买
    isActive: 0, //是否被选
    itemImg: '', //sku小图
    cartObject: {},
    showLogin: false, //是否展示登录
    showSkuList: false, //点击加入购物车展示购物车商品sku
    showPage: '', //页面加载后进行展示
    progressAnimation: '', //加载动画
    progressHeight: 3, //进度条高度
    progressPercent: 0, //进度条百分比
    progressOp: 1, //进度条透明度

    //---------------跳转url------------------------
    pageUrl: '',
    //---------------利润显示------------------------
    minFxFee: 0, //最小利润
    maxFxFee: 0, //最大利润
    minFxFeeRate: 0, //最小利润率
    maxFxFeeRate: 0, //最大利润率
    isViewFxFeeDetail: 0, //  小程序商品详情是否显示分销费用(1: 是 / 0: 否)

    //----------------百度地图数据------------------------------------------
    latitude: '', //经度
    longitude: '', //纬度
    placeData: {},

    //---商品相关---------------------------------------------------
    products: [], //所有商品
    product: '', //商品
    minPrice: 0, //最小价格（初始化商品价格范围）
    maxPrice: 0, //最大价格

    skuTitles: [], //sku中title
    skus: [], //所有sku内容
    distAttrs: [],
    chooseAttrids: [], //已选属性id
    isLimited: false, //是否为限购商品
    limitedNum: 0, //限购数量
    proImgs: [], //商品主图轮播

    //----------暂存购物车商品信息-------------------
    itemId: '', //暂存购物车商品id 
    skuId: '', //skuid
    count: 1, //购物车数量
    stock: 0, //默认库存
    toShow: '', //购物车弹窗类型；
    itemPrice: '', //商品显示价格
    showSmImg: false, //展示购物车小图
    //--------分享商品动画------------------------------

    shareImgUrl: '', //分享图片地址
    showCanvas: false, //用于生成图片
    codeUrl: '', //分享码地址
    // shareCanvasWidth:'',//预览窗口宽度
    left: '', //预览窗口偏移量
    isshowcanvasMask: false, //分享图片蒙层
    canvasImg: '', //后台合成小程序海报
    posterUrl: '', //海报资源路径
    shareProduct: false, //是否展示分享菜单
    showSettingBox: false, //打开引导用户设置弹出层
    authorizeMsg: '', //授权信息提示
    localPosterUrl: '', //本地海报路径

    //----------商品分享分享人inviter-店铺id------------------------------
    shopInfo: {}, //店铺信息，用于控制展示分销利润
    inviter: '', //分享人inviter(通过二维码扫描进入小程序获取)
    shopuid: '', //店铺id
    inShareShop: false, //是否有分享店铺
    isShareLink: false, //是否为分享的链接
    shareKey: '', //shareKey =='0'为分享标识

    //---------电话绑定情况--------------------
    isBindPhone: false,
    //------用户绑定手机操作-------------
    animationData: '', //遮罩层动画
    scorllTopAnimationData: '', //回到顶部动画
    showBindPhoneModel: false, //绑定手机模态框
    isPhone: false,
    phoneNum: '',//需要绑定的手机号
    //-----------购物车商品数量----------------------
    cartCount: 0,
    // ----------分享图片点击预览--------------------
    previewUrl: '', //生成分享图片临时地址
    //商品详情转化-------------------------
    itemDesc: '', //商品详情
    // ----------视频播放----------------------------
    showVideo: false, //是否播放视频
    // ---------缩放canvas动画------------------------------
    scaleAnimation: '', //缩放
    // 商品留言
    productLevMsgs: '', //商品留言[]
    levMsgImgs: [], //留言图片
    requireContent: {}, //验证提示项
    showErrMsg: false, //自定义验证消息提示窗是否显示
    errMsg: '', //错误消息
    hasErrMsg: '', //是否有错误信息提示
    errMsgAnimationData: '', //展示提示窗动画
    msgImgObj: {}, //需要上传图片的留言项

    //canvas北京高度宽度
    canvasWidth: '',
    canvasHeight: '',
    //海报自身宽高
    posterWidth: '',
    posterHeight: '',

    //拼团---------------------------
    showPinBox: false, //打开并选择拼团阶层 几级拼团
    zjgrouplevels: '', //拼团登记信息
    zjGroupLevelId: '', //拼团等级id
    groupInfo: '', //开团截止日期sku价格等等 roupPriceSkus 【】 itemGroupPrice	 availEndDate //拼团结束时间
    chooseGroupLevel: '', //已选的阶级信息
    showGroupList: false, //是否展示全部拼单列表窗口
    //拼团分享信息pinParms
    orderId: '', //拼单订单id
    showJoinPinPage: '', //展示参团界面
    zjGroupList: '', //参团人列表
    orderInfo: '', //拼团订单信息
    pinUser: '', //是否是通过拼单分享进来的用户 1是 0 不是
    zjGroupActivityVos: '', //正在拼团的用户列表
    // 限时折扣信息
    zjlimitdeprnPrice: '',
    // sku折扣以及限购数量
    skuDeprnRatio: '', //sku折扣

  },
  /**
   * 生命周期函数--监听页面加载，用于接收参数
   */
  onLoad: function(parameter) { //parameter--productId为商品id
    console.log('商品页所有参数', parameter);

    var that = this;
    //获取进度条进度
    that.getProgress();

    //本地店铺信息
    let shopInfo = wx.getStorageSync('shopInfo') || {};
    //商品id 和 分享人uid、店铺id,是否在分销店铺，转发标识
    let [productId, inviter, shopuid, shareKey, orderId] = [that.data.itemId, '', '', '', ''];

    //------列表页请求单个商品详细信息 ---------------------------------
    if (parameter.productId) {
      productId = parameter.productId; //商品id
      shopuid = parameter.shopuid || ''; //店铺id
    } else if (parameter.parms) { //通过转发分享进商品详情页
      let parms = parameter.parms.split('/');
      [productId, inviter, shopuid, shareKey] = parms;
    }
    //-----------通过扫描二维码 进入商品页 -----------------------------
    else if (parameter.q) {
      let scan_url = decodeURIComponent(parameter.q);
      let parm = scan_url.split('?')[1]; //当前所有参数
      let ids = parm.split('/');
      [productId, inviter, shopuid, shareKey] = ids;
    }
    //------------通过小程序码进入商品详情-------------------------------
    else if (parameter.scene) {
      let scene = decodeURIComponent(parameter.scene);
      let param = scene.split('/');
      let pinParms = scene.split(',');
      if (param.length == 4) {
        [productId, inviter, shopuid, shareKey] = param;
      } else if (pinParms.length == 4) {
        [orderId, inviter, shopuid, shareKey] = pinParms;
      }

    } else if (parameter.pinParms) {
      let pinParms = parameter.pinParms.split('/');
      orderId = pinParms[0];
      inviter = pinParms[1];
      shopuid = pinParms[2];
      shareKey = pinParms[3]; //分享的标识
      console.log('pinParms', pinParms);
    }
    //------------没有接收到参数-----------------------------------------
    else {
      console.log("请求缺少参数productId");
    }
    //空字符串拦截
    shopuid = (shopuid == "''" ? '' : shopuid);

    //设置参数
    that.setData({
      itemId: productId,
      inviter: inviter,
      shopuid: shopuid,
      shareKey: shareKey, //shareKey =='0'为分享标识
      scrollViewHeight: app.data.windowHeight, //滚动窗口高度
      windowWidth: app.data.windowWidth, //窗口宽度
      windowHeight: app.data.windowHeight, //窗口高度
      orderId: orderId,
    })
    console.log("商品id:" + productId + "分享人inviter:" + inviter + "店铺idshopuid:" + shopuid + 'shareKey:' + shareKey);

  },
  onShow: function() {
    let shareKey = this.data.shareKey;
    if (shareKey == '0' || shareKey == '1') { //分享标识,取消店铺过期标识
      app.recoverShopInfoTime();
    } else if (app.data.shopInfoTimeOut === true || shareKey == '') { //非分享且已经过期，清除店铺信息
      this.setData({
        shopuid: '',
        inviter: ''
      })
    }
    console.log('checkSession', this.data.shopuid, this.data.inviter);
    app.checkSession(this.data.shopuid, this.data.inviter); //携带分享店铺信息
    this.checkSessionTask();

  },
  //检查登录态
  checkSessionTask: function() {
    let that = this;

    let checkSessionTask = setInterval(function() {
      let isAuthorization = app.data.isAuthorization;

      if (isAuthorization === true || isAuthorization === false) {

        //返回店铺信息
        clearInterval(checkSessionTask); //结束任务

        if (isAuthorization) {
          rd_session = wx.getStorageSync('rd_session');
          if (that.data.showLogin === true) {
            that.cancelAnimation();
          }
          // let productId = that.data.productId
          if (that.data.product == '' && that.data.orderId == '') { //有shang拼id
            that.getItemInfo(); //获取商品详情页信息
          }
          if (that.data.orderId != '' && that.data.orderInfo == '') { //获取拼单信息 加载过避免重复加载
            that.getGroupOrderInfo(that.data.orderId); //查找拼团信息
          }

        } else { //未登录
          let showLogin = that.data.showLogin
          if (showLogin !== true) { //未展示登录
            that.loginAnimation();
            return;
          }
        }
      }

    }, 100)
  },
  // 获取拼团活动信息
  getGroupOrderInfo: function(orderId) {
    rd_session = wx.getStorageSync('rd_session');
    http.getReq('/weixin/groupActivity/findByOrderId', {
      orderId: orderId,
      rdSession: rd_session
    }, (res) => {
      console.log('加载拼团订单成功', res);
      let orderInfo = res.data;
      this.setData({
        pinUser: 1,
        orderId: orderId,
        orderInfo: orderInfo,
        zjGroupList: orderInfo.zjGroupActivityPeoples,
        zjGroupLevelId: orderInfo.zjGroupLevelId, //拼团级别getGroupLevel
        itemId: orderInfo.itemId,
      })
      //获取倒计时日期格式
      this.getTimeType(orderInfo.groupEndTime);
      //获取拼团头像列表
      this.getZjGroupList(orderInfo.needPeople);

      //获取chooseGroupLevel
      this.getGroupLevel();

      //获取商品信息
      if (this.data.product == '') {
        this.getItemInfo();
      }
    })
  },
  // 参与其他用户拼单
  handleJoinPinOrder: function(e) {
    console.log('handleJoinPinOrder', e);
    let orderId = e.currentTarget.dataset.id;
    this.getGroupOrderInfo(orderId);
    this.cancelGroupList();
  },
  /**
   * 拼团倒计时格式
   */
  getTimeType: function(groupEndTime) {
    let surplusTime = groupEndTime - (new Date()).getTime();
    console.log('surplusTime', surplusTime);

    this.setData({
      dateFormat: surplusTime > Day ? true : false,
      surplusTime: surplusTime
    })
  },
  /**
   * 获取拼团头像列表
   */
  getZjGroupList: function(needPeople) {
    if (needPeople > 0) {
      let zjGroupList = this.data.zjGroupList;
      for (let i = 0; i < needPeople; i++) {
        zjGroupList.push([]); //补全参人列表
      }
      this.setData({
        zjGroupList: zjGroupList
      })
    }
  },
  // 检查登录
  userLoginTask: function() {
    let that = this;
    let userLoginTask = setInterval(function() {
      let isAuthorization = app.data.isAuthorization;
      if (isAuthorization === true) {
        rd_session = wx.getStorageSync('rd_session');
        clearInterval(userLoginTask);
        if (that.data.showLogin === true) {
          that.cancelAnimation();
        }

        if (that.data.product == '' && that.data.orderId == '') { //有shang拼id
          that.getItemInfo(); //获取商品详情页信息
        }
        if (that.data.orderId != '' && that.data.orderInfo == '') { //获取拼单信息
          that.getGroupOrderInfo(that.data.orderId); //查找拼团信息
        }
      }
    }, 100)
    setTimeout(function() {
      let isAuthorization = app.data.isAuthorization;
      if (isAuthorization === false) {
        util.showToast('连接失败，请重试', 1000, 'none', function(res) {
          that.loginAnimation();
        })
      }
    }, 10000)
  },

  /**
   * 获取商品信息
   */
  getItemInfo: function() {

    this.setData({
      isAuthorization: app.data.isAuthorization,
      isBindPhone: wx.getStorageSync('isBindPhone'), //根据绑定状态获取用户授权
      cartCount: app.data.cartCount || wx.getStorageSync('cartCount'), //购物车数量；
    })
    this.QueryitemByItemId(); //根据店铺id 查商品
  },


  //---------------------------点击选择商品属性---------------------------------
  selectValue: function(e) {
    console.log('selectValue-app.data.limitedNum)',app.data.limitedNum);
    app.selectValue(e);
    //是否为折扣商品，折扣商品限购数去sku内的限购数
    let isZkPro = this.data.product.zjlimitdeprnPrice ? true : false;
    this.setData({
      distAttrs: app.data.distAttrs,
      chooseAttrids: app.data.chooseAttrids,
      itemId: app.data.itemId,
      skuId: app.data.skuId,
      stock: app.data.stock,
      count: app.data.count,
      itemPrice: app.data.itemPrice,
      itemImg: app.data.itemImg,
      skuDeprnRatio: app.data.skuDeprnRatio, //sku折扣
      limitedNum: isZkPro ? app.data.limitedNum : this.data.limitedNum, //sku限购数量
    })
    // console.log("selectValue:app.data.skuid---" + app.data.skuId);
    // console.log(this.data.itemPrice);
  },

  changeCount: function(e) { //改变数量
   // console.log('changeCount',e);
    app.changeCount(e, this);
    setTimeout(()=>{
      this.setData({
        count: app.data.count,
      })
    },200)
   
  },
  minsCount: function(e) { //减少数量
    app.minsCount(e, this);
    this.setData({
      count: app.data.count,
      stock: app.data.stock
    })
  },
  addCount: function(e) { //增加数量
   // console.log('addCount',e);
    app.addCount(e, this);
    this.setData({
      count: app.data.count
    })
  },
  getToBuy: function(e) { //是否为立即购买
    app.getToBuy(e);
    this.setData({
      toBuy: app.data.toBuy
    })
  },
  addmessage: function(e) { //选择商品信息
    var that = this;
    //---------------判断手机号是否绑定---------------
    let isBindPhone = wx.getStorageSync('isBindPhone');
    let product = that.data.product;
    let isLimited = product.isLimited; //判断该商品是否为限购商品
    let toShow = that.data.toShow || 'submit'; //购物车弹出 类型

    //改变购物车按钮样式
    if (e) {
      toShow = e.currentTarget.dataset.type;
      that.getToBuy(e);
    }
    that.setData({
      toShow: toShow
    })

    //如果是限购且未绑定手机
    if (isLimited == '1' && !isBindPhone) {
      //弹出绑定手机弹窗
      that.showBindTip(e);
      that.bindPhone(e);
      that.getToBuy(e); //用户是否点击了立即购买
      return;
    }
    //调用全局方法
    util.showLoading('加载中', (res) => {
      app.addmessage(this);
      app.getStock(this); //获取库存 若是拼团商品根据拼团zjGroupLevelId查询sku信息
      //更新商品以及商品库存
      let getStockTask = setInterval(() => {
        if (app.data.getStock === true) {
          clearInterval(getStockTask);
          app.getSkuValue(app.data.product); //getstock 后刷新skus属性获取sku所有属性
          this.makeAnimation(toShow); //弹出购物车动画
          //更新商品sku

          this.setData({
            toBuy: app.data.toBuy, //控制购买/下一步按钮状态
            skus: app.data.skus,
            skuTitles: app.data.skuTitles,
            distAttrs: app.data.distAttrs,
            cartProducts: app.data.cartProducts,
            chooseAttrids: app.data.chooseAttrids,
            itemId: app.data.itemId || this.data.itemId,
            skuId: app.data.skuId || this.data.skuId,
            count: app.data.count,
            stock: app.data.cartStock,
            product: app.data.product,
            skuDeprnRatio: app.data.skuDeprnRatio,
            itemPrice: app.data.itemPrice
          })
          wx.hideLoading();
        }
      }, 500)

    })
  },
  //------------------关闭/开启购物车动画----------------
  cancelAnimation: function(toCancel) {
    let that = this;
    app.cancelAnimation();
    this.setData({
      showSkuList: false,
      shareProduct: false,
      animationData: app.data.animationData, //加入购物车动画
    })
    //动画延时播放
    setTimeout(function() {
      that.setData({
        isshow: app.data.isshow,
        showLogin: app.data.showLogin,
        showSmImg: false, //展示购物车小图
        isLogin: false, //是否点击了登录按钮
        animationData: app.data.animationData, //加入购物车动画
      })
    }.bind(this), 300)
  },
  makeAnimation: function(toShow) {
    let that = this;
    let [showSkuList, shareProduct] = ['', ''];
    app.makeAnimation();

    //showSkuList、shareProduct分别为判断显示弹出内容
    if (toShow == 'add' || toShow == 'submit') { //播放加入购物车动画
      showSkuList = true;
    } else if (toShow == 'shareProduct') { //播放分享菜单动画
      shareProduct = true;
    }
    this.setData({
      isshow: app.data.isshow,
      showSkuList: showSkuList,
      shareProduct: shareProduct,
      animationData: app.data.animationData, //加入购物车动画
    })
    setTimeout(function() {
      that.setData({
        showSmImg: true,
        animationData: app.data.animationData, //加入购物车动画
      })
    }.bind(this), 100)
  },
  unAddMessage: function(e) { //关闭
    let toCancel = e.currentTarget.dataset.type; //关闭动画类型
    this.cancelAnimation(toCancel);
    app.unAddMessage();
    //是一键拼团界面
    let zjGroupLevelId = this.data.pinUser != '' ? this.data.zjGroupLevelId : '';
    setTimeout(() => {
      this.setData({
        toBuy: app.data.toBuy,
        showSmImg: false, //展示购物车小图
        skus: app.data.skus,
        distAttrs: app.data.distAttrs,
        chooseAttrids: app.data.chooseAttrids,
        itemId: app.data.itemId,
        skuId: app.data.skuId,
        count: app.data.count,
        stock: app.data.stock,
        itemPrice: app.data.itemPrice,
        itemImg: app.data.itemImg,
        showSkuList: false,
        zjGroupLevelId: zjGroupLevelId, //拼团id
        skuDeprnRatio:'',//sku折扣值
      })
      // console.log('itemId--' + app.data.itemId);
      // console.log('unAddMessage：skuId--' + app.data.skuId);
      // console.log('count--' + app.data.count);
      // console.log('stock--' + app.data.stock);
    }, 200)
  },

  validateSKU: function() { //对购物车所选sku 进行验证
    return app.validateSKU(this);
  },


  //加入购物车或跳转到订单详情页
  addCart: function(e) { //加入购物车

    //检查购物车数量
    if (app.data.cartCount >= 50){
      util.showToast('购物车数量已满，可以直接下单哦~', 2000)
      return false;
    }
    //自定义消息填写验证
    let productLevMsgs = this.data.productLevMsgs;
    if (productLevMsgs.length > 0) {
      this.validateMsgs(productLevMsgs);
      if (this.data.hasErrMsg) { //是否有错误提示信息
        return false
      }
      //保存自定义信息到本地
      this.saveProductLevMsgs(productLevMsgs);
    }

    //--------验证自定义项-------------------
    let that = this;
    //验证sku 
    let validate = that.validateSKU();
    if (validate) { //通过验证关闭动画
      let toCancel = e.currentTarget.dataset.type; //关闭动画类型
      that.cancelAnimation(toCancel); //关闭加入购物车窗口
    } else {
      return;
    }
    let pageUrl = that.data.pageUrl;
    if (e.currentTarget.dataset.pageurl) {
      pageUrl = e.currentTarget.dataset.pageurl;
    }
    that.setData({
      pageUrl: pageUrl,
    })
    app.addCart(e, that);
    //加入购物车后初始化count、
    let waitElementsCounts = setInterval(function() {
      if (app.data.cartCount != 0) {
        clearInterval(waitElementsCounts);
        that.setData({
          toBuy: app.data.toBuy,
          count: app.data.count,
          showLogin: app.data.showLogin,
          animationData: app.data.animationData,
          cartCount: app.data.cartCount
        })
      }
    }, 300)

  },
  //==================获取地理位置======================================
  getLocation: function() {
    let that = this;
    let placeData = that.data.placeData;
    if (placeData) {
      //打开剧场位置
      wx.openLocation({
        latitude: parseFloat(placeData.pointX),
        longitude: parseFloat(placeData.pointY),
        name: placeData.name,
        address: placeData.address,
        success: function(res) {
          console.log("打开剧场位置成功");
        }
      })
    }

  },
  //============回到主页================================================
  backToHome: function(e) { //返回到首页
    app.backToHome(this);
  },
  toCartPage: function() { //跳转到我的购物车
    let pageUrl = '/pages/shopingCart/shopingCart';
    let that = this;
    that.setData({
      pageUrl: pageUrl,
      toCartPage: true,
    })
    wx.switchTab({
      url: pageUrl
    })
  },

  //-------登陆动画-------------------
  loginAnimation: function() {
    app.loginAnimation();
    this.setData({
      isLogin: false,
      isAuthorization: app.data.isAuthorization,
      animationData: app.data.animationData,
      showLogin: app.data.showLogin,
    })
  },


  onShareAppMessage: function(options) { //微信分享
    console.log('转发途径:', options)
    // 分享来源，分享人id(谁转发 谁是分享人)
    let [that, shareFrom, inviter, product, shopInfo] = [this, options.from, wx.getStorageSync('unionid') || '', this.data.product, wx.getStorageSync('shopInfo')];
    let isAuthorization = app.data.isAuthorization;
    if (isAuthorization !== true) { //未登录播放登录动画
      that.loginAnimation();
      util.showToast('您还未登录，请在登陆后分享~', 2000, 'none', function() {});
      return;
    } else {
      // 转发所需参数商品id 和 分享人uid和 店铺id
      //分享标题、商品id、店铺id、分享图标
      let [shareTitle, productId, shopuid, shareImg, orderId] = [product.itemName, product.id, shopInfo.shopuid || '', product.itemimags[0].imgs, this.data.orderId];
      console.log("商品id" + productId + "分享人id" + inviter + "店铺shopuid" + shopuid);
      //通过分享菜单的按钮分享
      if (shareFrom !== 'menu') {
        that.cancelShare(options); //收起菜单
      }
      let shareUrl = ''; //转发打开链接路径
      let pinParms = orderId + '/' + inviter + '/' + shopuid + '/0'; //shareKey =1 拼单用户点击进入
      let parms = productId + '/' + inviter + '/' + shopuid + '/0'
      '/page/product/product?pinParms=' + pinParms
      if (orderId != '') { //拼单用户进来分享
        shareUrl = '/pages/home/home?pinParms=' + pinParms;
        shareTitle = '快来' + product.minGroupPrice + '起拼' + product.itemName;
      } else { //商品详情页分享
        shareUrl = '/pages/product/product?parms=' + parms;
      }
      return {
        title: shareTitle,
        imageUrl: shareImg,
        path: shareUrl
      }
    }

  },
  shareProduct: function(e) { //商品分享
    let shareType = e.currentTarget.dataset.type;
    let orderId = this.data.orderId;

    this.makeAnimation(shareType);
  },

  cancelShare: function(e) { //关闭分享菜单
    let toCancel = '';
    if (e) {
      toCancel = e.target.dataset.type; //关闭动画
    }
    this.cancelAnimation(toCancel);
  },

  saveShareImg: function(e) { //保存生成图片
    let that = this;
    let [canvasImg, localPosterUrl] = [this.data.canvasImg, this.data.localPosterUrl];
    if (localPosterUrl == '') {
      wx.downloadFile({
        url: canvasImg,
        success: (res) => {
          this.setData({
            localPosterUrl: res.tempFilePath
          })
        }
      })
    }
    let loadPosterTaks = setInterval(() => {
      localPosterUrl = this.data.localPosterUrl
      if (localPosterUrl !== '') {
        clearInterval(loadPosterTaks);
        wx.authorize({
          scope: 'scope.writePhotosAlbum',
          success: (rr) => {
            //生成图片保存本地
            console.log('canvasImg=>localPosterUrl', localPosterUrl);
            this.saveImageToPhone(localPosterUrl, e);
          },
          fail: (res) => {
            if (res.errMsg == 'saveImageToPhotosAlbum:fail cancel') { //取消选择
              this.setData({
                showCanvas: false,
                showSettingBox: false,
              })
            } else {
              util.showToast("请授权‘保存到相册’，否则无法保存图片到相册", '', 'none', () => {
                this.setData({
                  showCanvas: false,
                  showSettingBox: true,
                })
                return
              });
            }
          }
        })
      }

    }, 100)


  },
  //打开设置 授权‘保存图片到相册’
  authorizeSaveImg: function(path, e) {
    wx.openSetting({
      success: (setInfo) => {
        let openInfo = setInfo.authSetting;
        if (openInfo['scope.writePhotosAlbum']) {
          this.cancelSettingBox();
          this.saveImageToPhone(path, e);
        }
      }
    })
  },
  //保存图片到手机相册
  saveImageToPhone: function(path, e) {

    if (path) {
      wx.saveImageToPhotosAlbum({
        filePath: path,
        success: (save_res) => {
          util.showToast('保存成功', 1000, 'none', function() {});
          if (this.data.showSettingBox) {
            this.cancelSettingBox();
          }
          this.cancelShare(e);
          //收起菜单 隐藏绘画
          this.cancelShareImg();
        },
        fail: (ee) => {
          console.log('fail', ee);
        }

      })
    }



  },
  //关闭分享图片
  cancelShareImg: function() {
    console.log("关闭分享图片");
    this.cancelAnimation();
    this.setData({
      showCanvas: false,
      isshowcanvasMask: false
    })
  },
  //拨打电话
  makePhoneCall: function(e) {
    console.log(e);
    let telnum = e.currentTarget.dataset.telnum;
    wx.showModal({
      content: '拨打' + telnum + '?',
      showCancel: true,
      cancelText: '取消',
      confirmText: '确定',
      success: function(res) {
        if (res.confirm) {
          wx.makePhoneCall({
            phoneNumber: telnum,
            success: function(res) {
              console.log("拨打电话");
            }
          })
        }
      }
    })
  },
  //弹出绑定提示
  showBindTip: function(e) {
    let that = this;
    util.showToast('该商品需要绑定手机，请您先绑定手机后操作', 1500, 'none', function() {
      setTimeout(function() {
        that.bindPhone(e);
      }, 1000)
    });
  },

  //---------------用户绑定手机号弹出框-------------------------
  bindPhone: function (e) {
    console.log('用户绑定手机号', e);
    wx.hideTabBar(); //隐藏底部菜单
    http.getReq('/weixin/wxUser/getWxPhone', {
      encryptedData: e.detail.encryptedData,
      iv: e.detail.iv,
      rdSession: wx.getStorageSync('rd_session')
    }, (res) => {
      console.log('bindPhone-', res);
      let [phoneNum, isPhone] = [res.data.purePhoneNumber, true]

      if (!res.ret) {
        util.showToast(res.msg, 1000, 'none');
        isPhone = false
      }
      this.setData({
        showBindPhoneModel: true,
        isshow: true,
        phoneNum: phoneNum || '',//需要绑定的手机号
        isPhone: isPhone,
      })
    })
  },
  //保存手机号 
  savePhone: function(e) {
    this.closeModel(e);
    this.setData({
      isBindPhone: e.detail.isBindPhone,
    })
  },
  //关闭绑定模态框
  closeModel: function(e) {
    this.setData({
      showBindPhoneModel: e.detail.showBindPhoneModel,
      isshow: false
    });
    wx.showTabBar(); //显示底部菜单
  },
  //手机预览图片
  previewImage: function(e) {
    app.previewImage(e);
  },
  //------------根据商品id查商品信息---------------------------------------------------------
  QueryitemByItemId: function() {
    let [that, shopuid, productId] = [this, '', this.data.itemId]; //商品id

    //用于显示在商品详情内显示用户的利润信息
    //用于根据session查看店铺内是上架分享过来的商品
    let shopInfo = wx.getStorageSync('shopInfo');
    shopuid = shopInfo ? shopInfo.shopuid : shopuid;
    console.log('rd_session', rd_session);
    console.log('shopuid', shopuid);
    console.log("商品id:" + productId + "店铺idshopuid:" + shopuid + 'rd_session' + rd_session);
    http.getReq('/weixin/item/QueryitemByItemId', {
      productId: productId,
      shopuid: shopuid || '',
      rdSession: rd_session
    }, function(res) {
      console.log('返回商品信息', res);
      let [product, orderId] = [res.data, that.data.orderId];

      if (res.ret) {
        // 图片为空替换默认图片
        if (!product.itemimags[0]) {
          let itemimags = {};
          itemimags.imgs = app.data.defaultImgUrl;
          product.itemimags.push(itemimags);
        }

        let [placeData, itemDesc, posterUrl, skus, skuPrices, proImgs] = [product.sysTheatre || null, product.itemDescImg || '', product.posterUrl, product.skus, [],
          []
        ]; //地址信息,商品详情 ,获取海报资源路径、主图轮播

        let [minPrice, maxPrice] = [0, 0]; //价格区间
        let [minFxFee, maxFxFee, minFxFeeRate, maxFxFeeRate, isViewFxFeeDetail] = [that.data.minFxFee, that.data.maxFxFee, , that.data.minFxFeeRate, that.data.maxFxFeeRate, that.data.isViewFxFeeDetail];
        minFxFee = product.minFxFee || minFxFee;
        maxFxFee = product.maxFxFee || maxFxFee;
        minFxFeeRate = product.minFxFeeRate || minFxFeeRate;
        maxFxFeeRate = product.maxFxFeeRate || maxFxFeeRate;
        isViewFxFeeDetail = product.isViewFxFeeDetail || isViewFxFeeDetail;

        //获取价格区间
        if (skus.length > 0) {
          for (let s = 0; s < skus.length; s++) {
            if (product.zjlimitdeprnskuPrice){//是折扣商品
              skuPrices.push(skus[s].deprnPrices);
            }else{
              skuPrices.push(skus[s].price);
            }
          }
          if (skuPrices.length > 0) {
            minPrice = Math.min(...skuPrices);
            maxPrice = Math.max(...skuPrices);
          }
        } else {
          minPrice = product.price;
          maxPrice = product.price;
        }
        //商品主图轮播
        for (let i = 0; i < product.itemimags.length; i++) {
          proImgs.push(product.itemimags[i].imgs);
        }

        //获取chooseGroupLevel
        if (orderId != '') { //
          that.getGroupLevel(product.zjgrouplevels);
        }
        //字符串替换
        itemDesc = itemDesc.replace('<h2d-title">', '<h2d-title>');
        itemDesc = itemDesc.replace('<div">', '<div>');
        itemDesc = itemDesc.replace('<p">', '<p>');
        itemDesc = itemDesc.replace('</p">', '</p>');
        itemDesc = itemDesc.replace('</div">', '</div>');
        itemDesc = itemDesc.replace('</h2d-title">', '</h2d-title>');

        //获取留言信息
        that.checkAndViewLevMsgs(res.data.productLevMsgs || '');

        //获取海报尺寸
        //更新本地数据
        that.setData({
          zjlimitdeprnPrice: product.zjlimitdeprnPrice,
          showLoadding: false,
          minPrice: minPrice,
          maxPrice: maxPrice,
          product: product,
          showPage: true,
          placeData: placeData, //商品地理位置信息
          itemDesc: itemDesc, //商品详情
          proImgs: proImgs, //商品主图轮播
          limitedNum: product.limitedNum,//限购数量
          minFxFee: minFxFee,
          maxFxFee: maxFxFee,
          minFxFeeRate: minFxFeeRate || '',
          maxFxFeeRate: maxFxFeeRate,
          isViewFxFeeDetail: isViewFxFeeDetail,
          shopInfo: shopInfo, //店铺信息，用于控制展示分销利润
          zjgrouplevels: product.zjgrouplevels || '', //拼团等级信息
          zjGroupActivityVos: product.zjGroupActivityVos || '', //拼团用户列表
        })
        //html转化view商品详情
        WxParse.wxParse('itemDesc', 'html', itemDesc, that, 5);


        // that.progressAnimation();

        //下载海报文件资源到本地
        wx.downloadFile({
          url: posterUrl || product.itemimags[0].imgs, //商品图片地址
          success: function(sres) {
            //设置商品信息
            that.setData({
              posterUrl: sres.tempFilePath //海报资源路径
            })
          }
        })
      } else { //该店铺内查询不到此商品信息
        wx.showModal({
          title: '提示',
          content: '该商品在店铺内已下架，去看看别的吧~',
          showCancel: false,
          confirmText: '知道了',
          success: function(res) {
            console.log('没有商品跳转到home欢迎页');
            app.backToHome(this);
          }
        })
      }

    });


  },
  //获取拼单chooseGroupLevel
  getGroupLevel: function(zjgrouplevels = this.data.zjgrouplevels) {
    let zjGroupLevelId = this.data.zjGroupLevelId;

    for (let i = 0; i < zjgrouplevels.length; i++) {
      if (zjgrouplevels[i].id == zjGroupLevelId) {
        this.setData({
          chooseGroupLevel: zjgrouplevels[i]
        })
      }
    }

  },
  getMapRoute: function() {
    let placeData = JSON.stringify(this.data.placeData);
    wx.navigateTo({
      url: '/pages/product/pages/map-route/map-route?placeData=' + placeData
    })
  },
  scrollFun: function(e) {

    let [scrollTop, showTopBtn] = [e.detail.scrollTop, this.data.showTopBtn]
    if (scrollTop > 600 && !showTopBtn) {
      var animation = wx.createAnimation({
        duration: 500,
        timingFunction: 'ease',
      })
      this.animation = animation
      animation.translateX(-50).opacity(0.8).step();
      this.setData({
        scorllTopAnimationData: animation.export(),
        showTopBtn: true
      })
    }
    if (scrollTop <= 600) {
      var animation = wx.createAnimation({
        duration: 500,
        timingFunction: 'ease',
      })
      this.animation = animation
      animation.translateX(0).opacity(0).step();
      //回到顶部按钮
      this.setData({
        scorllTopAnimationData: animation.export(),
        showTopBtn: false
      })
    }
  },
  returnTop: function() { //回到顶部事件
    this.setData({
      scroll_top: 0,
      showTopBtn: false
    })
  },
  selloutTip: function() { //售空提示
    util.showToast('该商品已售罄,再看看别的商品吧', 1000, 'none', function() {});
  },
  //用户登录
  getUserInfo: function(e) {

    //查看是否允许授权
    let [that, errMsg] = [this, e.detail.errMsg];

    if (errMsg == 'getUserInfo:ok') {

      that.setData({
        isLogin: true, //是否点击登录按钮
      })

      app.userLogin(e, this.data.shopuid, this.data.inviter);
      that.userLoginTask(); //检查登录+加载商品信息

    } else { //未授权，打开设置

      //设置登录按钮状态
      that.setData({
        isLogin: false, //此时用户可点击登录按钮
      })
      app.connectionTimeout('请允许获得您的公开信息（头像、昵称）用于登录');

    }
  },

  //替换轮播图加载不出时图片
  errSwiperImg: function(e) {
    let proImgs = this.data.proImgs; //轮播商品图片
    let imgIndex = e.currentTarget.dataset.imgindex; //商品下标
    proImgs[imgIndex] = app.data.defaultImgUrl;
    this.setData({
      proImgs: proImgs
    })
  },

  getFormId: function(e) {
    app.getFormId(e);
  },
  //获取进度条加载进度
  getProgress: function() {
    //页面加载进度条
    let that = this;
    progress = setInterval(function() {
      let showPage = that.data.showPage
      let progressPercent = that.data.progressPercent;
      let progressOp = that.data.progressOp; //进度条透明度
      if (showPage) {
        progressPercent = 100;
      } else {
        if (progressPercent < 90) { //进度条
          progressPercent++;
        }
      }

      if (progressOp > 0.5) { //进度条透明度
        progressOp = progressOp - 0.05;
      }

      //并且把当前的进度值设置到progress中
      that.setData({
        progressPercent: progressPercent, //比例
        progressOp: progressOp //透明度
      })

      //当进度条为100时清除定时任务
      if (progressPercent >= 100) {

        // that.progressAnimation();        
        clearInterval(progress);
        var changeProgressHeight = setInterval(function() { //改变进度条高度任务
          let progressHeight = that.data.progressHeight;
          if (progressHeight == 0) {
            clearInterval(changeProgressHeight); //清除

          } else {
            progressHeight -= 1;
          }
          that.setData({
            progressHeight: progressHeight
          })
        }, 10)
      }
    }, 5);

  },
  //隐藏进度条动画
  progressAnimation: function() {
    let that = this;
    var animation = wx.createAnimation({
      duration: 500,
      timingFunction: 'ease',
    })

    this.animation = animation

    animation.opacity(0).height(0).step()

    this.setData({
      progressAnimation: animation.export()
    })
  },
  //打开设置，保存海报
  bindopensetting: function(e) {

    let that = this;
    let errMsg = e.detail.errMsg;
    let authSetting = e.detail.authSetting['scope.writePhotosAlbum'];
    if (authSetting == true) { //同意授权
      this.saveImageToPhone(that.data.localPosterUrl, e);
    }

  },
  cancelSettingBox: function() { //关闭设置提示窗
    this.setData({
      showSettingBox: false
    })
  },
  showSettingBox: function() { //打开设置提示窗
    app.showSettingBox();
    this.setData({
      showSettingBox: app.data.showSettingBox,
      authorizeMsg: '保存图片到相册', //授权信息提示
    })
  },

  onHide: function() {
    this.setData({
      shareKey: '',
      zjGroupLevelId: ''
    })
  },
  //----------------------自定义项方法--------------------------------------
  // 查看留言信息
  checkAndViewLevMsgs: function(productLevMsgs = this.data.productLevMsgs) {
    if (!productLevMsgs) return; //如果没有留言信息

    for (let i = 0; i < productLevMsgs.length; i++) {
      let msgItem = productLevMsgs[i];
      //获取文件格式
      productLevMsgs[i].type = app.getLevMsgType(msgItem.fieldType);
      productLevMsgs[i].value = ''; //用户存普通数据
      productLevMsgs[i].datetime = []; //用于存日期时间数据
      productLevMsgs[i].hasErrMsg = null; //用于存日期时间数据
    }
    console.log('查看留言信息productLevMsgs', productLevMsgs);

    this.setData({
      productLevMsgs: productLevMsgs,

    })
  },

  //选择自定义图片1张
  chooseMsgImage: function(e) {
    console.log('choosePhoto', e);
    let id = e.currentTarget.dataset.id;
    let productLevMsgs = this.data.productLevMsgs;
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      success: (res) => {
        console.log(res);
        let msgImgObj = {}; //上传照片对象
        for (let i = 0; i < productLevMsgs.length; i++) {
          if (id == productLevMsgs[i].zjItemMessageId) {
            productLevMsgs[i].value = res.tempFilePaths[0]; //保存图片路径
            msgImgObj.src = res.tempFilePaths[0]; //保存图片路径
            msgImgObj.id = id;
            this.setData({
              productLevMsgs: productLevMsgs,
              msgImgObj: msgImgObj
            })
            this.validateMsgs(productLevMsgs, i); //验证填写
          }
        }
      },
    })
  },
  //选择自定义项日期
  bindMsgDateChange: function(e) {
    console.log('bindMsgDateChange', e);
    let id = e.currentTarget.dataset.id;
    let productLevMsgs = this.data.productLevMsgs;
    let value = e.detail.value;
    for (let i = 0; i < productLevMsgs.length; i++) {
      if (id == productLevMsgs[i].zjItemMessageId) {
        let type = productLevMsgs[i].type;
        //判断是否为日期时间类型
        if (type == 'datetime') {
          productLevMsgs[i].datetime[0] = value;
        } else {
          productLevMsgs[i].value = value;
        }
        this.setData({
          productLevMsgs: productLevMsgs
        })
        this.validateMsgs(productLevMsgs, i); //验证填写
      }
    }

  },
  //选择自定义项时间
  bindMsgTimeChange: function(e) {
    console.log('bindMsgTimeChange', e);
    let id = e.currentTarget.dataset.id;
    let productLevMsgs = this.data.productLevMsgs;
    let value = e.detail.value;
    for (let i = 0; i < productLevMsgs.length; i++) {
      if (id == productLevMsgs[i].zjItemMessageId) {
        let type = productLevMsgs[i].type;
        //判断是否为日期时间类型
        if (type == 'datetime') {
          productLevMsgs[i].datetime[1] = value;
        } else {
          productLevMsgs[i].value = value;
        }
        this.setData({
          productLevMsgs: productLevMsgs
        })
        this.validateMsgs(productLevMsgs, i); //验证填写
      }
    }
  },
  //保存自定义输入框value
  saveMsgValue: function(e) {
    console.log('saveMsgValue', e);
    let id = e.currentTarget.dataset.id;
    let productLevMsgs = this.data.productLevMsgs;
    let value = e.detail.value;

    for (let i = 0; i < productLevMsgs.length; i++) {
      if (id == productLevMsgs[i].zjItemMessageId) {
        productLevMsgs[i].value = value;
        this.setData({
          productLevMsgs: productLevMsgs,
        })

        this.validateMsgs(productLevMsgs, i); //验证填写

      }
    }
  },
  //验证自定义信息填写规则
  /**
   * 验证自定义信息填写规则
   * @验证的所有的自定义项--array
   * @需要验证到什么位置的下标--msgIndex
   */
  validateMsgs: function(productLevMsgs, msgIndex) {

    let requireContent = {}; //返回验证项提示
    let requireItem = []; // 需要晚上和填写的项目
    let requireMsg = [];
    for (let i = 0; i < productLevMsgs.length; i++) {

      let value = productLevMsgs[i].value; //要素值
      let type = productLevMsgs[i].type; //要素类型
      let required = productLevMsgs[i].required; //是否必填
      let fieldName = productLevMsgs[i].fieldName; //要素名称
      let datetime = productLevMsgs[i].datetime; //日期时间
      let hasErrorVal = '';
      let errMsg = '';

      if (required) { //必填项
        if (value == '' && type != 'datetime') {
          requireItem.push(fieldName);
          hasErrorVal = true;
        }
      }

      if (type == 'datetime') { //日期时间格式
        if ((datetime.length > 0 && !required) || (required && datetime.length !== 2)) {
          if (!datetime[0]) {
            requireItem.push('日期');
            hasErrorVal = true;
          }
          if (!datetime[1]) {
            requireItem.push('时间');
            hasErrorVal = true;
          }
        }
      }

      //非必填项也需要验证的项目
      //手机号验证
      if (type == 'number' && value != '') {
        errMsg = util.testPhone(value) ? '' : fieldName + '格式错误';
      }

      //验证身份证
      if (type == 'idcard' && value != '') {
        errMsg = util.testIdCard(value) ? '' : fieldName + '格式错误';
      }

      //验证邮箱
      if (type == 'email' && value != '') {
        errMsg = util.testEmile(value) ? '' : fieldName + '格式错误';
      }

      if (errMsg != '') {
        requireMsg.push(errMsg);
        hasErrorVal = true;
      }

      if (hasErrorVal) { //有错误提示信息
        productLevMsgs[i].hasErrMsg = true;
      } else {
        if (value !== '' || datetime.length == 2) { //值不为空
          productLevMsgs[i].hasErrMsg = false;
        } else { //值为空
          productLevMsgs[i].hasErrMsg = '';
        }

      }


      // 如果有需要验证的下标
      if (msgIndex >= 0 && i == msgIndex) {
        break;
      }
    }

    //验证项提示
    requireContent.requireItem = requireItem; //需要填写项目 []
    requireContent.requireMsg = requireMsg; //填写错误提示 ''

    this.setData({
      requireContent: requireContent,
      productLevMsgs: productLevMsgs,
      hasErrMsg: (requireMsg.length > 0 || requireItem.length > 0) ? true : false //是否有错误消息
    })

    this.showErrMsg(requireContent); //提示动画

  },

  //自定义消息验证未通过提示动画
  showErrMsg: function(requireContent) {
    let errMsg = ''; //消息提示
    let requireItem = requireContent.requireItem;
    let requireMsg = requireContent.requireMsg;

    if (requireItem.length > 0) { //消息提示
      errMsg = '请填写 ' + requireItem.join(' ');
    } else if (requireMsg.length > 0) {
      errMsg = requireMsg[0];
    }
    if (errMsg) {
      //创建动画
      var animation = wx.createAnimation({

        duration: 500,
        timingFunction: "ease",
        delay: 0,
        transformOrigin: "50% 50%",

      })
      //第一步先将动画放在要出现之前的位置
      animation.translateY(-40).step();
      this.setData({
        errMsg: errMsg,
        errMsgAnimationData: animation.export(),
        showErrMsg: true
      })

      setTimeout(() => {
        animation.translateY(0).step();
        this.setData({
          errMsgAnimationData: animation.export(),
        })
      }, 50)

      setTimeout(() => {
        animation.translateY(-40).step()
        this.setData({
          errMsgAnimationData: animation.export(),
        })
        setTimeout(() => {
          this.setData({
            showErrMsg: false
          })
        }, 500)
      }, 1500)
    }

  },
  //保存自定义信息到本地
  saveProductLevMsgs: function(productLevMsgs) {

    app.saveProductLevMsgs(productLevMsgs, this.data.msgImgObj);
    let product = this.data.product;
    product.productLevMsgs = productLevMsgs;
    this.setData({
      product: product
    })
  },
  //展示拼团窗口
  showPinType: function(e) {
    let zjgrouplevels = this.data.zjgrouplevels; //团购阶级信息
    if (zjgrouplevels.length == 1) {
      //只有一个阶团购 直接请求数据 显示下一步
      this.setData({
        zjGroupLevelId: zjgrouplevels[0].id || '',
        chooseGroupLevel: zjgrouplevels[0] //已选拼团类型
      })
      this.addmessage(e);
    } else {
      this.setData({
        showPinBox: true,
        isshow: true
      })
    }



  },
  //选择拼团类型
  handlePinType: function(e = '') {
    console.log('handlePinType', e);
    let zjGroupLevelId = this.data.zjGroupLevelId;
    let chooseGroupLevel = ''; //已选的阶级信息
    let id = e.currentTarget.dataset.id;

    if (id == zjGroupLevelId && zjGroupLevelId !== '') return; //有已选id
    let zjgrouplevels = this.data.zjgrouplevels;
    for (let i = 0; i < zjgrouplevels.length; i++) {
      if (zjgrouplevels[i].id == id) {
        zjgrouplevels[i].checked = true;
        chooseGroupLevel = zjgrouplevels[i];
      } else {
        zjgrouplevels[i].checked = false;
      }
    }
    this.setData({
      zjgrouplevels: zjgrouplevels,
      zjGroupLevelId: id,
      chooseGroupLevel: chooseGroupLevel
    })
  },
  // 确定拼团类型并查询查询拼团的sku价格
  confirmPinType: function(e) {
    let zjGroupLevelId = this.data.zjGroupLevelId;
    let zjgrouplevels = this.data.zjgrouplevels;

    if (zjGroupLevelId == '') {
      let hasId = false;
      for (let i = 0; i < zjgrouplevels.length; i++) {
        if (zjgrouplevels[i].checked == true) {
          zjGroupLevelId = zjgrouplevels[i].id;
          hasId = true;
        }
      }
      if (!hasId) {
        util.showToast('请选择团类型', '', 'none');
        return;
      }
    }
    this.setData({
      showPinBox: false,
      zjGroupLevelId: zjGroupLevelId, //已选拼团id
    })
    //根据sku 展示购物车
    this.addmessage(e);

  },
  // 关闭拼团窗口
  cancelPinType: function() {
    this.setData({
      showPinBox: false,
      isshow: false
    })
  },

  //打开拼单列表；
  handerShowGroupList: function() {
    this.setData({
      showGroupList: true, //是否展示全部拼单列表窗口
      isshow: true
    })
  },
  //关闭拼单列表
  cancelGroupList: function() {
    this.setData({
      showGroupList: false, //是否展示全部拼单列表窗口
      isshow: false
    })
  },
  /**
   *复制 copyText
   */
  copyText: function(e) {
    util.copyText(e);
  },
  /**
   * 未开售提示
   */
  unSoldTip: function() {
    util.showToast('商品还未开售，可先添加到购物车。', 1500, 'none');
  },
  /**
   * 从后台获取商品海报
   */
  getCodePoster: function() {
    //分享参数------------------------------------------
    let shopInfo = wx.getStorageSync('shopInfo');
    let [that, shopuid, requestUrl, product, orderId] = [this, shopInfo.shopuid || '', '', this.data.product, this.data.orderId];
    let [canvasImg, localPosterUrl] = [this.data.canvasImg, this.data.localPosterUrl];
    if (canvasImg != '') {
      this.setData({
        isshowcanvasMask: true,
        showCanvas: true
      })
    } else {
      http.getReq('/weixin/poster/generate', {
        rdSession: rd_session,
        sceneStr: product.id, //商品id
        shopuid: shopuid, //店铺id
        orderId: orderId, //拼团商品
        page: "pages/product/product", //小程序跳转路径
      }, (res) => {
        console.log('getCodePoster', res);
        let canvasImg = res.data;
        wx.getImageInfo({
          src: canvasImg,
          success: (rr) => {
            let [canvasWidth, canvasHeight, rate] = [rr.width, rr.height, 1]; //canvas宽高 图片比例
            if (canvasWidth > 500 || canvasWidth < 449) { //宽大于500，按比例缩小生成图片大小
              rate = (500 / canvasWidth).toFixed(2);
            }

            this.setData({
              isshowcanvasMask: true,
              showCanvas: true,
              canvasWidth: canvasWidth * rate,
              canvasHeight: canvasHeight * rate,
              canvasImg: canvasImg,
            })

          },
        })

      }, true, '生成中')
    }


  },
  /**
   * 改变时间转换类型
   */
  changeFormat:function(e){
    this.setData({
      dateFormat: e.detail
    })
  }


})